const drag = {
    data() {
        return {
            Sortable: null,
        }
    },
    methods: {
        sortable(that, container, element, callback) {
            var $ul = that.$el.querySelector(container)
            $ul.addEventListener('selectstart', function (e) {
                e.preventDefault();
            })
            this.Sortable = Sortable.create($ul, {
                handle: element,
                draggable: element,
                animation: 150,
                onUpdate: (event) => {
                    let newIndex = event.newIndex, oldIndex = event.oldIndex;
                    $li = $ul.children[newIndex],
                        $oldLi = $ul.children[oldIndex]
                    //先删除移动的节点, 再插入移动的节点到原有节点，还原了移动的操作
                    $ul.removeChild($li)
                    if (newIndex > oldIndex) {
                        $ul.insertBefore($li, $oldLi)
                    } else {
                        $ul.insertBefore($li, $oldLi.nextSibling)
                    }
                    //通过改变vue遍历数组移动节点
                    callback(newIndex, oldIndex);
                }
            })
        }
    }
}
new Vue({
    el: '#app',
    data() {
        return {
            form: {
                Page_Group_SerialNumber: '',
                Page_Group_Name: '',
                Enterprise_Info_SerialNumber: $.cookie('enterprise'),
                Children: {
                    page_type: [{
                        Page_Type_SerialNumber: createUniqueString(),
                        Page_Group_SerialNumber: '',
                        Page_Type_Name: '新增页面1',
                        Parent_Page_SerialNumber: '',
                        Path: '',
                        Leven: '',
                        Page_SerialNumber: '',
                    }]
                }
            },
            Data: [],
            Type: [],
            Group: [],
            PageGroup: [],//方案
            loading: false,
        }
    },
    mixins: [drag],
    mounted() {
        this.sortable(this, '#page_type', '.el-descriptions', (newIndex, oldIndex) => {
            let item = this.form.Children.page_type[oldIndex];
            this.form.Children.page_type.splice(oldIndex, 1);
            this.form.Children.page_type.splice(newIndex, 0, item);
        });
    },
    computed: {
        treeData() {
            let items = this.form.Children.page_type
            // 创建一个以id为键，值为对应对象的映射  
            const map = {};
            items.forEach(item => {
                map[item.Page_Type_SerialNumber] = { ...item, children: [] }
            });
            // 遍历所有项，将每个项添加到其父项的children数组中  
            items.forEach(item => {
                const parentId = item.Parent_Page_SerialNumber;
                if (parentId && map[parentId]) {
                    map[parentId].children.push(map[item.Page_Type_SerialNumber]);
                }
            });
            // 提取根节点（即parentId为null或未定义的项）  
            const rootNodes = items.filter(item => !item.Parent_Page_SerialNumber || map[item.Parent_Page_SerialNumber] === undefined).map(item => map[item.Page_Type_SerialNumber]);
            // 如果只需要根节点的数组，返回它  
            return rootNodes;
        }
    },
    methods: {
        submitForm(formName) {
            let _this = this
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    _this.loading = true
                    if (_this.form.Parent_Page) {
                        _this.form.Leven = parseInt(_this.Parent.filter(i => i.Page_SerialNumber == _this.form.Parent_Page)[0].Leven) + 1
                    } else {
                        _this.form.Leven = 1
                    }
                    if (this.form.End_Date == null) {
                        this.form.End_Date = ''
                    }
                    $.ajax({
                        url: `${DomainName}/getAddAction?token=${$.cookie('token')}`,
                        type: 'POST',
                        data: {
                            Data: JSON.stringify({
                                page_group: [_this.form]
                            }),
                            Operation_Name: '添加页面方案'
                        },
                        success: function (res) {
                            if (res.Status === 'success') {
                                _this.$message.success("提交成功")
                                window.history.go(-1);
                            } else {
                                _this.$message.error("提交失败，请稍后再试")
                            }
                        },
                        error: function () {
                            _this.$message.error("操作失败，请稍后再试")
                        },
                        complete: function (XMLHttpRequest) {
                            _this.loading = false
                            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                                window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                            }
                        }
                    })
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        add_page_type() {
            this.form.Children.page_type.push({
                Page_Type_SerialNumber: createUniqueString(),
                Page_Group_SerialNumber: '',
                Page_Type_Name: '新增页面'+(this.form.Children.page_type.length+1),
                Parent_Page_SerialNumber: '',
                Path: '',
                Leven: '',
                Page_SerialNumber: '',
            })
        },
        remove_page_type() {
            if (this.form.Children.page_type.length>1) {
                this.form.Children.page_type.pop()
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                  })
            }
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    }
})